package com.example.socket.server.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @author xurongbei
 */
public class SocketServer {

    private static ExecutorService service = Executors.newFixedThreadPool(100);

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9000);

        serverDemo(serverSocket);
        //serverDemoMulty(serverSocket);
    }

    /**
     * 多线程
     * 缺点：资源浪费不够用
     * @param serverSocket
     * @throws IOException
     */
    private static void serverDemoMulty(ServerSocket serverSocket) throws IOException {
        while (true){
            System.out.println("等待链接---");
            //阻塞方法
            Socket clientSocket = serverSocket.accept();
            System.out.println("有客户端连接了---");
            new Thread(() -> {
                try {
                    handler(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

        }
    }

    /**
     * 线程池
     * 缺点：虽然没有浪费问题，但是还是解决不了并发量大的问题
     * @param serverSocket
     * @throws IOException
     */
    private static void serverThreadPoll(ServerSocket serverSocket) throws IOException{
        while (true){
            System.out.println("等待链接---");
            //阻塞方法
            Socket clientSocket = serverSocket.accept();
            System.out.println("有客户端连接了---");
            service.submit(() -> {
                try {
                    handler(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

        }
    }


    /**
     * 单线程，无法处理并发问题
     * @param serverSocket
     * @throws IOException
     */
    private static void serverDemo(ServerSocket serverSocket) throws IOException {
        while (true){
            System.out.println("等待链接---");
            //阻塞方法
            Socket clientSocket = serverSocket.accept();
            System.out.println("有客户端连接了---");
            handler(clientSocket);
        }
    }

    private static void handler(Socket clientSocket) throws IOException {
        byte[] bytes = new byte[1024];
        System.out.println("准备read。。");
        //接收客户端的数据，阻塞方法，没有数据可读时就阻塞
        int read = clientSocket.getInputStream().read(bytes);
        System.out.println("read完毕。。");
        if(read!=-1){
            System.out.println("接收到客户端的数据："+new String(bytes,0,read));
        }

        System.out.println("end");

    }
}
